/*
 * @Description: 可编辑表格
 * @Date: 2023-06-02 09:44:43
 * @Author: jiao-xiao-lin
 */
import React, { memo, useMemo, useState } from 'react';
import { Table, Button, Form, Typography, Popconfirm, message } from 'antd';
import { unstable_batchedUpdates as batchUpdateState } from 'react-dom';

import { createExcelFile } from '@/utils/fileFunc';
import { cloneDeep, forEach, findIndex } from 'lodash';
import PropTypes from 'prop-types';
import styles from './index.less';
import EditableCell from './EditableCell';
import {
  addHeatSourceCfg,
  deleteHeatSourceCfg,
  updateHeatSourceCfg,
} from '@/api/game_managememnt';

export const EditTable = (props) => {
  const {
    // 列表展示的数据
    dataSource = [],
    // 表头的数据
    columns = [],
    // 表格行 key 的取值
    rowKey = 'key',
    // rowClassNameConfig背景色配置项: 1.修改背景色key的取值 2.rowClassName:行类名
    rowClassNameConfig = {},
    // excel文件展示的列配置项
    excelColumns = [],
    // 选择类型 checkbox | radio 空为不可选择
    selectMode = '',
    // 是否显示新增按钮
    ifAddBtn = true,
    // 是否显示导出按钮
    ifExportBtn = false,
    // fontsizeStyleConfig 字体样式配置:1.baseKey 字段标识 2.baseValue基准值 3.defaultClassName默认类名 4.specialClassName 特殊类名
    fontsizeStyleConfig = {},
    setList = null,
  } = props;
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState(''); // 是否可编辑的key标识
  const [selectedRowKeys, setSelectedRowKeys] = useState(''); // checkbox已选项key集合
  const [selectData, setSelectData] = useState([]); // 已选的行数据
  const [ifAdd, setIfAdd] = useState(false); // 是否新增状态
  const [oldProduct, editBtn] = useState(0);
  const isEditing = (record) => {
    return record.lowShellTemperatureThreshold === editingKey;
  };

  // 添加
  const handleAdd = () => {
    setIfAdd(true);
    let newData = cloneDeep(dataSource);
    const lowShellTemperatureThreshold = newData.length + 1;
    if (editingKey !== '' && newData.length) {
      //如果上一条还处于编辑状态，不可新增
      message.error('请先保存');
      return;
    }
    const arr = Object.keys(dataSource);
    let data = {};
    // forEach(arr, (item) => {
    //   data[item] = '';
    // });
    const row = {
      lowShellTemperatureThreshold,
    };
    newData.push(row);
    batchUpdateState(() => {
      setList(newData);
      setEditingKey(lowShellTemperatureThreshold);
    });
    // 表单重置
    form.setFieldsValue({
      projectId: '',
      product: '',
      heatSource: '',
      remark: '',
      updateUserId: '',
      updateUserName: '',
      updateTime: '',
      lowShellTemperatureThreshold: 0,
    });
  };

  // 编辑行
  const edit = (record) => {
    // 点击编辑按钮，存储当前点击行的产品号
    editBtn(record.product);
    form.setFieldsValue(record);
    batchUpdateState(() => {
      setEditingKey(record.lowShellTemperatureThreshold);
      setIfAdd(false);
    });
  };
  23;

  // 获取行的样式类型
  const getRowClassName = (record) => {
    let className = '';
    if (record?.[rowClassNameConfig?.key] > rowClassNameConfig?.baseValue) {
      className = rowClassNameConfig?.rowClassName;
    }
    return className;
  };

  // 删除行
  const deleteRow = async (dataSource, index) => {
    if (dataSource[index].product) {
      await deleteHeatSourceCfg({
        projectId: '614',
        product: dataSource[index].product,
      });
    }
    dataSource.splice(index, 1);
    const arr = cloneDeep(dataSource);
    setList(arr);
  };

  // 取消创建、编辑
  const cancel = (dataSource, index) => {
    if (ifAdd) {
      // dataSource.splice(1, 1)
      deleteRow(dataSource, index);
    }
    setEditingKey('');
  };

  // 保存
  const save = async (record) => {
    try {
      let row = await form.validateFields();
      const newData = cloneDeep(dataSource);
      // findIndex: 返回符合条件的元素索引，否则返回-1
      const index = findIndex(
        newData,
        (item) =>
          record.lowShellTemperatureThreshold ===
          item.lowShellTemperatureThreshold,
      );
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        newData[index].projectId = '614';
        // 根据ifAdd判断是否新增保存还是编辑保存
        if (ifAdd) {
          // 新增保存
          const res = await addHeatSourceCfg(newData[index]);
        } else {
          // 编辑保存
          let par = {
            projectId: newData[index].projectId,
            product: newData[index].product,
            heatSource: newData[index].heatSource,
            remark: newData[index].remark,
            updateUserId: newData[index].updateUserId,
            updateUserName: newData[index].updateUserName,
            oldProduct: String(oldProduct),
            lowShellTemperatureThreshold:
              newData[index].lowShellTemperatureThreshold,
          };
          const res = await updateHeatSourceCfg(par);
        }
      } else {
        newData.push(row);
      }
      batchUpdateState(() => {
        setList(newData);
        setEditingKey('');
      });
    } catch (errInfo) {}
    // setIfAdd(false)
  };

  // 取消选中项
  const cancelRowSelection = () => {
    setSelectedRowKeys([]);
  };

  // 复选框配置项
  const listRowSelection = {
    type: selectMode,
    onChange: (selectedRowKeys, selectedRows) => {
      batchUpdateState(() => {
        setSelectedRowKeys(selectedRowKeys);
        setSelectData(selectedRows);
      });
    },
    selectedRowKeys,
  };

  // 导出行数据
  const exportExcel = (list) => {
    if (!list?.length) {
      message.info('请先勾选！');
      return false;
    }
    createExcelFile({ list, columns: excelColumns });
    message.success('导出成功！');
    cancelRowSelection();
  };

  const tableColumns = useMemo(() => {
    const { baseKey, baseValue, defaultClassName, specialClassName } =
      fontsizeStyleConfig;
    return columns.map((item) => {
      const { key, editable, dataIndex, type, title } = item;
      if (key === 'i') {
        return {
          ...item,
          render: (text, record, index) => {
            return index + 1;
          },
        };
      }
      if (key === baseKey) {
        return {
          ...item,
          render: (text, record, index) => {
            return (
              <span
                className={
                  text > baseValue ? specialClassName : defaultClassName
                }
              >
                {text || '--'}
              </span>
            );
          },
          // 可编辑单元格配置项
          onCell: editable
            ? (record, index) => ({
                record,
                type,
                inputType: 'text',
                dataIndex,
                title,
                editing: isEditing(record),
              })
            : null,
        };
      }
      if (key === 'operate') {
        return {
          ...item,
          render: (text, record, index) => {
            const editable = isEditing(record);

            return (
              <div className={styles.operate}>
                <div className={styles.left}>
                  {!editable ? (
                    <Button
                      type="link"
                      disabled={editingKey !== ''}
                      onClick={() => edit(record)}
                    >
                      编辑
                    </Button>
                  ) : (
                    <span>
                      <Typography.Link
                        onClick={() => save(record)}
                        style={{
                          marginRight: 8,
                        }}
                      >
                        保存
                      </Typography.Link>
                      <Popconfirm
                        title={ifAdd ? `确认取消创建？` : '确认取消编辑?'}
                        onConfirm={() => cancel(dataSource, index)}
                      >
                        <a>取消</a>
                      </Popconfirm>
                    </span>
                  )}
                </div>
                {!editable && (
                  <div className={styles.right}>
                    <Button
                      type="link"
                      disabled={editingKey !== ''}
                      onClick={() => deleteRow(dataSource, index)}
                    >
                      删除
                    </Button>
                  </div>
                )}
              </div>
            );
          },
        };
      }

      return {
        ...item,
        render: (text) => {
          return <>{text || '--'}</>;
        },
        // 可编辑单元格配置项
        onCell: editable
          ? (record, index) => ({
              record,
              inputType: 'text',
              dataIndex,
              title,
              type,
              editing: isEditing(record),
            })
          : null,
      };
    });
  }, [columns, dataSource, editingKey]);

  const tabProps = {
    components: {
      body: {
        cell: EditableCell,
      },
    },
    dataSource,
    columns: tableColumns,
    rowKey,
    rowClassName: getRowClassName,
    rowSelection: selectMode ? listRowSelection : null,
  };

  return (
    <div className={styles.commonTab}>
      {(ifAddBtn || ifExportBtn) && (
        <div className={styles.buttonArea}>
          {ifAddBtn && (
            <Button type="default" onClick={handleAdd} className={styles.add}>
              添加
            </Button>
          )}
          {ifExportBtn && (
            <Button
              type="default"
              onClick={() => {
                exportExcel(selectData);
              }}
            >
              导出
            </Button>
          )}
        </div>
      )}
      <div>
        <Form form={form} component={false}>
          <Table {...tabProps} />
        </Form>
      </div>
    </div>
  );
};
EditTable.propTypes = {
  dataSource: PropTypes.array,
  columns: PropTypes.array,
  rowKey: PropTypes.string,
  rowClassNameConfig: PropTypes.object,
  setList: PropTypes.func,
  fontsizeStyleConfig: PropTypes.object,
  excelColumns: PropTypes.array,
  selectMode: PropTypes.bool,
  ifAddBtn: PropTypes.bool,
  ifExportBtn: PropTypes.bool,
};

export default memo(EditTable);
